import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hixing_app/models/options_model.dart';

///
/// Email: k1041153622@gmail.com
/// @author chris
/// @date 2024/05/10
/// @desc  通用的 swicher
///
const _bgColor = Colors.grey;

class SwitchBoxNotifier extends ChangeNotifier {
  double _left = 0;
  final List<double> _widthList = [];
  double _scrollOffset = 0;
  Duration _boxDuration = Duration.zero;

  double get left => _left;

  List<double> get widthList => _widthList;

  double get scrollOffset => _scrollOffset;

  Duration get boxDuration => _boxDuration;

  set left(double value) {
    _left = value;
    notifyListeners();
  }

  addWidthList(double value) {
    widthList.add(value);
    notifyListeners();
  }

  set scrollOffset(double value) {
    _scrollOffset = value;
    notifyListeners();
  }

  set boxDuration(Duration value) {
    _boxDuration = value;
    notifyListeners();
  }
}

class CustomSwitcher extends StatefulWidget {
  CustomSwitcher({
    super.key,
    this.index = 0,
    required this.switchList,
    required this.onTap,
  }) : assert(switchList.isNotEmpty, "数据列表不能为空");

  final int index;
  final List<OptionsModel> switchList;
  final void Function(OptionsModel) onTap;

  @override
  State<CustomSwitcher> createState() => _CustomSwitcherState();
}

class _CustomSwitcherState extends State<CustomSwitcher> {
  late final ThemeData _themeData = Theme.of(context);

  double right = 0;
  int _index = 0;
  bool isFirst = true;
  ScrollController scrollController = ScrollController();
  SwitchBoxNotifier boxNotifier = SwitchBoxNotifier();

  @override
  void initState() {
    super.initState();
    scrollController.addListener(onScroll);
    setState(() {
      _index = widget.index;
    });
  }

  @override
  void dispose() {
    scrollController.removeListener(onScroll);
    boxNotifier.dispose();
    scrollController.dispose();
    super.dispose();
  }

  void onScroll() {
    boxNotifier.scrollOffset = scrollController.offset;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 42.w,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: _bgColor,
        borderRadius: BorderRadius.circular(8),
        // border: Border.all(color: _themeData.primaryColor),
      ),
      child: LayoutBuilder(builder: (ctx, size) {
        /// 滚动不准的问题，可以监听滚动的offset来修正偏移量
        return Stack(
          children: [
            ListenableBuilder(
              listenable: boxNotifier,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.orangeAccent,
                  borderRadius: BorderRadius.circular(6),
                ),
              ),
              builder: (ctx, child) {
                return AnimatedPositioned(
                  duration: boxNotifier.boxDuration,
                  left: boxNotifier.left - boxNotifier.scrollOffset,
                  bottom: 0,
                  child: AnimatedContainer(
                    duration: boxNotifier.boxDuration,
                    height: size.maxHeight,
                    width: boxNotifier.widthList.isEmpty
                        ? 0
                        : boxNotifier.widthList[_index],
                    child: child,
                  ),
                );
              },
            ),
            ListView(
                scrollDirection: Axis.horizontal,
                controller: scrollController,
                physics: const ClampingScrollPhysics(),
                children: List.generate(widget.switchList.length, (itemIndex) {
                  var itemData = widget.switchList[itemIndex];
                  Color color = itemIndex == _index
                      ? _themeData.colorScheme.onSecondary
                      : Colors.grey.withOpacity(0.4);
                  return Builder(builder: (ctx) {
                    Future.microtask(
                      () {
                        if (ctx.findRenderObject() != null &&
                            boxNotifier.widthList.length !=
                                widget.switchList.length) {
                          // 找到当前组件的 RenderBox 对象
                          RenderBox? renderBox =
                              ctx.findRenderObject() as RenderBox;
                          // 获取实际宽度
                          double width = renderBox.size.width;
                          print('Width: $width');

                          boxNotifier.addWidthList(width);
                          if (boxNotifier.widthList.length ==
                              widget.switchList.length) {}
                        }
                      },
                    );

                    return GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        if (_index == itemIndex) return;
                        boxNotifier.boxDuration =
                            const Duration(milliseconds: 200);
                        if (itemIndex == 0) {
                          boxNotifier.left = 0;
                        } else {
                          double currentLeft = 0;
                          for (int i = 0; i < itemIndex; i++) {
                            currentLeft += boxNotifier.widthList[i];
                          }
                          boxNotifier.left = currentLeft;
                        }
                        setState(() {
                          _index = itemIndex;
                        });
                        widget.onTap(itemData);
                        Future.delayed(const Duration(milliseconds: 200), () {
                          boxNotifier.boxDuration = Duration.zero;
                        });
                      },
                      child: Container(
                        height: 42.w,
                        padding: EdgeInsets.symmetric(
                            vertical: 4.w, horizontal: 10.w),
                        child: Container(
                          alignment: Alignment.center,
                          child: AnimatedDefaultTextStyle(
                            duration: const Duration(milliseconds: 200),
                            style: TextStyle(
                                color: itemIndex == _index
                                    ? Colors.black
                                    : Colors.white,
                                fontWeight: itemIndex == _index
                                    ? FontWeight.bold
                                    : FontWeight.normal,
                                fontSize: 12.w),
                            child: Text(
                              itemData.label,
                            ),
                          ),
                        ),
                      ),
                    );
                  });
                })),
          ],
        );
      }),
    );
  }
}
